<template>
  <div class="weather">
    <div class="weather-header">
      <headerPhoto>
        <div class="search">
          <input @keyup.enter="getSearchDataFn" v-model="message" type="text" placeholder="请输入需查询地址的市或区名...">
          <i @click="getSearchDataFn" class="bi bi-search text-light"></i>
        </div>
        <div class=" history d-flex">
          <div v-for="(item, index) in historyArr" :key="index" class="box">
            <span @click="clickHistoryFn(item)" class="me-1">{{ item }}</span>
            <i @click="delHistoryFn(index)" class="bi bi-backspace-fill"></i>
          </div>
        </div>
      </headerPhoto>
    </div>
    <waveView></waveView>
    <div class="container">
      <div class="location text-center">
        {{ locationData.province }} {{ locationData.city }} {{ locationData.name }}
      </div>
      <div class="content pb-5">
        <table v-if="weatherArr.length > 0" class=" table table-bordered table-hover mt-5 my_table">
          <thead>
            <tr class="text-center">
              <th class="opt" scope="col">#</th>
              <th scope="col">日期</th>
              <th class="opt" scope="col">星期</th>
              <th scope="col">白天</th>
              <th scope="col">晚上</th>
              <th scope="col">温度</th>
            </tr>
          </thead>
          <tbody>
            <tr class="text-center" v-for="(item, index) in weatherArr" :key="index">
              <th class="opt" scope="row">{{ index + 1 }}</th>
              <td>{{ item.date }}</td>
              <td class="opt">{{ item.week }}</td>
              <td>天气：{{ item.text_day }}<br />
                风力：{{ item.wc_day }}
              </td>
              <td>天气：{{ item.text_night }}<br />
                风力：{{ item.wc_night }}
              </td>
              <td>{{ item.low }}℃ ~ {{ item.high }}℃</td>
            </tr>
          </tbody>
        </table>
        <div v-else class="message text-center ">
          暂无搜索结果
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import headerPhoto from "@/component/headerPhoto.vue";
import waveView from "@/component/waveView.vue";
import { getWeather } from "@/api/index";
import { ref } from "vue";
import { Toast } from "vant";
import { cityData } from "@/static/data/cityData"
import { ElMessage } from 'element-plus'

// 搜索的内容
const message = ref<string>('');
const historyArr = ref<string[]>([]);


interface ILocation {
  [key: string | number]: string | number
}
const locationData = ref<ILocation>({});

if (localStorage.getItem('wearth')) {
  historyArr.value = JSON.parse(localStorage.getItem('wearth') || '[]')
}
interface IWeather {
  [key: string | number]: string | number
}
// 文章列表数组
const weatherArr = ref<IWeather[]>([])

// 自动获取当前定位
const getLocationFn = async () => {
  navigator.geolocation.getCurrentPosition(
    async (position) => {
      // console.log(position)
      // 纬度
      const latitude = position.coords.latitude;
      // 经度
      const longitude = position.coords.longitude;
      const location = `${longitude},${latitude}`;
      await getWeatherFn(location)
    },
    err => {
      console.log("经纬度请求失败", err)
    }
  )
}

getLocationFn()


// 获取天气数据
const getWeatherFn = async (location: string) => {
  Toast.loading('正在查询...')
  // console.log(location)
  return await getWeather({ location })
    .then(
      res => {
        // console.log(res.data)
        if (res.status == 200) {
          weatherArr.value = res.data.data.result.forecasts
          locationData.value = res.data.data.result.location
          return true
        } else {
          return false
        }
        // console.log(weatherArr.value)
        // console.log(locationData.value)
      },
      err => {
        console.log("请求失败", err)
        return false
      }
    ).finally(() => {
      Toast.clear()
    })
}


// 获取搜索数据
const getSearchDataFn = async () => {
  if (!message.value.trim()) {
    ElMessage({
      message: '请输入地址~~',
      type: 'warning',
      plain: true,
      offset: 100
    })
    return false
  }
  getHistoryFn()

  await getData(message.value)
  message.value = ''
}

// 点击查询
const getData = async (text: string) => {
  let location = '';
  for (let i = 0; i < cityData.length; i++) {
    if (cityData[i]?.city.indexOf(text) != -1 || cityData[i]?.area.indexOf(text) != -1) {
      location = cityData[i]?.lng + ',' + cityData[i]?.lat;
      break
    }
  }
  const status = await getWeatherFn(location)
  // console.log(status)
  if (status) {
    ElMessage({
      message: '查询成功~~',
      type: 'success',
      plain: true,
      offset: 100
    })
  } else {
    ElMessage({
      message: '查询失败~~',
      type: 'error',
      plain: true,
      offset: 100
    })
  }
}
// 添加历史记录
const getHistoryFn = () => {
  if (!message.value) return false
  const index = historyArr.value.indexOf(message.value);
  if (index != -1) {
    historyArr.value.splice(index, 1)
  }
  historyArr.value.push(message.value)
  if (historyArr.value.length > 5) {
    historyArr.value.shift()
  }
  localStorage.setItem('wearth', JSON.stringify(historyArr.value))
  // console.log(historyArr.value)
}

// 删除历史记录
const delHistoryFn = (index: number) => {
  // console.log(index)
  historyArr.value.splice(index, 1);
  localStorage.setItem('wearth', JSON.stringify(historyArr.value))
}
// 点击历史记录搜索
const clickHistoryFn = (item: string) => {
  message.value = item
  // console.log(item)
  getHistoryFn()
  getData(message.value)
  message.value = ''
}

</script>

<style lang="less" scoped>
.weather-header {
  .search {
    width: 300px;
    height: 40px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 2px solid #d6fe67;
    border-radius: 20px;

    input {
      width: calc(100% - 40px);
      height: 100%;
      border-radius: 15px;
      border: none;
      outline: none;
      padding-left: 15px;
      background-color: transparent;
      color: #fff;

      &::-webkit-input-placeholder {
        color: rgb(255, 255, 255);
      }
    }

    i {
      display: block;
      width: 30px;
      height: 30px;
      font-size: 18px;
      background-size: cover;
    }
  }


  .history {
    width: 100%;
    margin: 0 auto;
    justify-content: center;
    flex-wrap: wrap;

    .box {
      color: #4790f7;
      background-color: #fff;
      margin: 10px 5px 0;
      padding: 0 5px;
      border-radius: 7px;
      font-size: 15px;

      span {
        cursor: pointer;
        vertical-align: middle;
      }

      i {
        &:hover {
          cursor: pointer;
          color: rgb(249, 114, 114);
        }
      }
    }
  }

}

.location {
  font-size: 25px;
}

.message {
  font-size: 20px;
  color: #666;
}

@media (max-width: 768px) {
  .opt {
    display: none;
  }
}
</style>
